package com.itmuch.cloud.study.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Joiner;
import com.itmuch.cloud.study.entity.*;
import com.itmuch.cloud.study.service.ItemBarService;
import com.itmuch.cloud.study.service.TransportDetailService;
import com.itmuch.cloud.study.service.TransportService;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class TransportServiceImpl implements TransportService {

    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private TransportDetailService transportDetailService;

    @Autowired
    private ItemBarService itemBarService;

    String url = "http://qr.huggies.com.cn/q/";

    //创建订单


    @Override
    public String saveOrderwitEntity(Transport transport, List<TransportDetail> transportDetails) {
        String result = "{\"msg\": \"保存失败\",\"success\": false}";

        /**
         * 当重复录入相同的delivery号时：
         *      根据delivery号查询订单是否存在
         *          如果存在：根据订单ID查询明细，查询该明细是否已经有扫描的物料，
         *              如果没有：删除该订单以及对应的明细，重新录入
         *          如果不存在，直接录入
         */
        List<Transport> trans = findByDelivery(transport.getDelivery());
        if (trans != null && trans.size() != 0) {
            //查询明细
            List<TransportDetail> details = transportDetailService.findDetailByTransportIdAndMaterialId(trans.get(0).getId(), "");
            if (details != null && details.size() != 0) {
                List<String> ids = new ArrayList<String>();
                for (TransportDetail td :
                        details) {
                    ids.add(td.getId());
                }
                //判断是否已经扫描
                boolean b = transportDetailService.findIsScanByDetailIds(ids);
                if (!b) {
                    //没有扫描直接删除
                    transportDetailService.deleteDetailByTransportId(trans.get(0).getId());
                    deleteTransportByid(trans.get(0).getId());
                } else {
                    result = "{\"msg\": \"delivery号已经存在且扫描，不能录入\",\"success\": false}";
                    return result;
                }
            }

        }


        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String transportId = UUID.randomUUID().toString();
        String delAddress = "";
        String delivery = "";
        String descRoute = "";
        String docDate = "";
        String orderRemark = "";
        String plantCode = "";
        String plantName = "";
        String poNum = "";
        String routeCode = "";
        String sendDate = "";
        String shipTo = "";
        String shipToName = "";
        String soldTo = "";
        String soldToName = "";
        String tel = "";


        if (!transport.getDelAddress().equals("") && transport.getDelAddress() != null) {
            delAddress = transport.getDelAddress();
        } else {
            return "{\"msg\": \"请填写收货地址\",\"success\": false}";
        }
        if (transport.getDelivery() != null && !transport.getDelivery().equals("")) {
            delivery = transport.getDelivery();
        } else {
            return "{\"msg\": \"请填写送货单号\",\"success\": false}";
        }
        if (transport.getDescRoute() != null && !transport.getDescRoute().equals("")) {
            descRoute = transport.getDescRoute();
        }

        if (transport.getDocDate() != null && !transport.getDocDate().equals("")) {
            String doc = transport.getDocDate();
            Date docTime = null;
            try {
                docTime = sdf.parse(doc);
            } catch (ParseException e1) {
                return "{\"msg\": \"凭证日期格式错误（yyyymmdd Eg:20161206）\",\"success\": false}";
            }
            docDate = sdf.format(docTime);
            //	docDate=transport.getDocDate();
        } else {
            return "{\"msg\": \"请填写凭证日期（yyyymmdd Eg:20161206）\",\"success\": false}";
        }
        if (transport.getOrderRemark() != null && !transport.getOrderRemark().equals("")) {
            orderRemark = transport.getOrderRemark();
        }
        if (transport.getPlantCode() != null && !transport.getPlantCode().equals("")) {
            plantCode = transport.getPlantCode();
        } else {
            return "{\"msg\": \"请填写工厂代码\",\"success\": false}";
        }
        if (transport.getPlantName() != null && !transport.getPlantName().equals("")) {
            plantName = transport.getPlantName();
        } else {
            return "{\"msg\": \"请填写工厂名称\",\"success\": false}";
        }
        if (transport.getPoNum() != null && !transport.getPoNum().equals("")) {
            poNum = transport.getPoNum();
        } else {
            return "{\"msg\": \"请填写参考凭证\",\"success\": false}";
        }
        if (transport.getRouteCode() != null && !transport.getRouteCode().equals("")) {
            routeCode = transport.getRouteCode();
        }
        if (transport.getSendDate() != null && !transport.getSendDate().equals("")) {
            String doc = transport.getSendDate();
            Date docTime = null;
            try {
                docTime = sdf.parse(doc);
            } catch (ParseException e1) {
                return "{\"msg\": \"要求交货日期格式错误（yyyymmdd Eg:20161206）\",\"success\": false}";
            }
            sendDate = sdf.format(docTime);
        } else {
            return "{\"msg\": \"请填写要求交货日期（yyyymmdd Eg:20161206）\",\"success\": false}";
        }
        if (transport.getShipTo() != null && !transport.getShipTo().equals("")) {
            shipTo = transport.getShipTo();
        } else {
            return "{\"msg\": \"请填写送达方编码\",\"success\": false}";
        }
        if (transport.getShipToName() != null && !transport.getShipToName().equals("")) {
            shipToName = transport.getShipToName();
        } else {
            return "{\"msg\": \"请填写送达方名称\",\"success\": false}";
        }
        if (transport.getSoldTo() != null && !transport.getSoldTo().equals("")) {
            soldTo = transport.getSoldTo();
        } else {
            return "{\"msg\": \"请填写售达方编码\",\"success\": false}";
        }
        if (transport.getSoldToName() != null && !transport.getSoldToName().equals("")) {
            soldToName = transport.getSoldToName();
        } else {
            return "{\"msg\": \"请填写售达方名称\",\"success\": false}";
        }
        if (transport.getTel() != null && !transport.getTel().equals("")) {
            tel = transport.getTel();
        }

        //循环判断订单下的每一条明细的必填字段，是否符合要求

        for (int i = 0; i < transportDetails.size(); i++) {
            if (transportDetails.get(i).getItem() == null || transportDetails.get(i).getItem().equals("")) {
                return "{\"msg\": \"请填写第" + (i + 1) + "条明细行号(item)\",\"success\": false}";
            }

            if (transportDetails.get(i).getOrderNo() == null || transportDetails.get(i).getOrderNo().equals("")) {
                return "{\"msg\": \"请填写第" + (i + 1) + "条订单号(orderNo)\",\"success\": false}";
            }

            if (transportDetails.get(i).getMaterial() == null || transportDetails.get(i).getMaterial().equals("")) {

                return "{\"msg\": \"请填写第" + (i + 1) + "条物料号(material)\",\"success\": false}";
            }

            if (transportDetails.get(i).getDescription() == null || transportDetails.get(i).getDescription().equals("")) {

                return "{\"msg\": \"请填写第" + (i + 1) + "条描述(description)\",\"success\": false}";
            }

            if (transportDetails.get(i).getDeliveryQty() == null || transportDetails.get(i).getDeliveryQty().equals("")) {

                return "{\"msg\": \"请填写第" + (i + 1) + "条发货数(deliveryQty)\",\"success\": false}";
            }

            if (transportDetails.get(i).getUnit() == null || transportDetails.get(i).getUnit().equals("")) {

                return "{\"msg\": \"请填写第" + (i + 1) + "条规格(unit)\",\"success\": false}";
            }

        }


        String sql1 = " insert into t_port(id,delAddress,delivery,descRoute,docDate,orderRemark,plantCode,"
                + "plantName,poNum,routeCode,sendDate,shipTo,shipToName,soldTo,soldToName,tel,createTime)values('" +
                transportId + "','" + delAddress + "','" + delivery + "','" + descRoute + "','" + docDate + "','" + orderRemark + "','" +
                plantCode + "','" + plantName + "','" + poNum + "','" + routeCode + "','" + sendDate + "','" + shipTo + "','" +
                shipToName + "','" + soldTo + "','" + soldToName + "','" + tel + "',NOW()) ";
        int count = jdbcTemplate.update(sql1);
        if (count != 1) {
            return result;
        }


        try {
            int[] updatedCountArray = jdbcTemplate.batchUpdate(" insert into t_portdetail(id,transportId,item,orderNo,refItm,material,description,"
                    + "productCode,custMaterial,locStorage,deliveryQty,unit,remark) values(?,?,?,?,?,?,?,?,?,?,?,?,?)", new BatchPreparedStatementSetter() {

                @Override
                public void setValues(PreparedStatement ps, int i) throws SQLException {

                    String item = "";
                    String orderNo = "";
                    String refItm = "";
                    String material = "";
                    String description = "";
                    String productCode = "";
                    String custMaterial = "";
                    String locStorage = "";
                    Double deliveryQty = 0.0;
                    String unit = "";
                    String remark = "";


                    if (!transportDetails.get(i).getItem().equals("")) {
                        item = transportDetails.get(i).getItem();
                    }
                    if (!transportDetails.get(i).getOrderNo().equals("")) {
                        orderNo = transportDetails.get(i).getOrderNo();
                    }
                    if (!transportDetails.get(i).getRefItm().equals("")) {
                        refItm = transportDetails.get(i).getRefItm();
                    }
                    if (!transportDetails.get(i).getMaterial().equals("")) {
                        material = transportDetails.get(i).getMaterial();
                    }
                    if (!transportDetails.get(i).getDescription().equals("")) {
                        description = transportDetails.get(i).getDescription();
                    }
                    if (!transportDetails.get(i).getProductCode().equals("")) {
                        productCode = transportDetails.get(i).getProductCode();
                    }
                    if (!transportDetails.get(i).getCustMaterial().equals("")) {
                        custMaterial = transportDetails.get(i).getCustMaterial();
                    }
                    if (!transportDetails.get(i).getLocStorage().equals("")) {
                        locStorage = transportDetails.get(i).getLocStorage();
                    }

                    if (!transportDetails.get(i).getDeliveryQty().equals("")) {
                        deliveryQty = Double.parseDouble(transportDetails.get(i).getDeliveryQty());
                    }
                    if (!transportDetails.get(i).getUnit().equals("")) {
                        unit = transportDetails.get(i).getUnit();
                    }

                    if (!transportDetails.get(i).getRemark().equals("")) {
                        remark = transportDetails.get(i).getRemark();
                    }


                    ps.setString(1, UUID.randomUUID().toString());
                    ps.setString(2, transportId);
                    ps.setString(3, item);
                    ps.setString(4, orderNo);
                    ps.setString(5, refItm);
                    ps.setString(6, material);
                    ps.setString(7, description);
                    ps.setString(8, productCode);
                    ps.setString(9, custMaterial);
                    ps.setString(10, locStorage);
                    ps.setDouble(11, deliveryQty);
                    ps.setString(12, unit);
                    ps.setString(13, remark);
                }

                @Override
                public int getBatchSize() {
                    return transportDetails.size();
                }
            });
            int sumInsertdCount = 0;
            for (int i : updatedCountArray) {
                sumInsertdCount += i;
            }

            result = "{\"msg\": \"订单保存成功！共'" + sumInsertdCount + "'条明细\",\"success\": true}";

        } catch (Exception e) {
            // TODO: handle exception
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return result;
        }
        return result;
    }


    @Override
    public List<Transport> findAll() {
        String sql = "select * from t_port";
        List<Transport> transports = jdbcTemplate.query(sql, new TransportMapper());
        return transports;
    }

    protected class TransportMapper implements RowMapper {

        public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
            Transport transport = new Transport();
            transport.setId(rs.getString("id"));
            transport.setPlantCode(rs.getString("plantCode"));
            transport.setDelivery(rs.getString("delivery"));

            return transport;
        }

    }

    //根据delivery查询订单信息
    @Override
    public List<Transport> findByDelivery(String delivery) {
        // TODO Auto-generated method stub
        StringBuffer sBuffer = new StringBuffer("select * from t_port where delivery = '" + delivery + "'");
        List<Transport> lists = null;
        try {
            lists = jdbcTemplate.query(sBuffer.toString(), new RowMapper<Transport>() {

                @Override
                public Transport mapRow(ResultSet rs, int rowNum) throws SQLException {
                    // TODO Auto-generated method stub
                    Transport transport = new Transport();
                    transport.setId(rs.getString("id"));
                    transport.setDelivery(rs.getString("delivery"));
                    transport.setSendDate(rs.getString("sendDate"));
                    transport.setPoNum(rs.getString("poNum"));
                    transport.setPlantName(rs.getString("plantName"));
                    transport.setShipToName(rs.getString("shipToName"));
                    transport.setPlantCode(rs.getString("plantCode"));
                    transport.setShipTo(rs.getString("shipTo"));
                    transport.setSoldTo(rs.getString("soldTo"));
                    return transport;
                }
            });

        } catch (Exception e) {
            // TODO: handle exception
            return null;
        }

        return lists;
    }

    //保存扫描信息
    @Override
    public String saveDeliverySkubarcode(String delivery, String barCode) {
        Message message = new Message();
        JSONObject jo = new JSONObject();
        //绑定扫描关系
        MaterialTransport mTransport = bindDeliverAndMaterial(delivery, barCode);
        List<MaterialTransport> lists = null;
        if (mTransport == null) {
            lists = getAllDeliverySkubarcode(delivery, "");
            message.setMsg("此二维码不存在");
            message.setSuccess("false");
        } else if (mTransport.getFlag() != null && mTransport.getFlag().equals("BPP")) {
            lists = getAllDeliverySkubarcode(delivery, "");
            message.setMsg("二维码与单号物料不匹配");
            message.setSuccess("false");

        } else if (mTransport.getFlag() != null && mTransport.getFlag().equals("SEND")) {
            lists = getAllDeliverySkubarcode(delivery, "");
            message.setMsg("已结单");
            message.setSuccess("false");

        } else if (mTransport.getFlag() != null && mTransport.getFlag().equals("NO")) {
            lists = getAllDeliverySkubarcode(delivery, "");
            message.setMsg(mTransport.getDescription());
            message.setSuccess("false");

        } else if (mTransport.getFlag() != null && mTransport.getFlag().equals("FULL")) {
            lists = getAllDeliverySkubarcode(delivery, "");
            message.setMsg("已扫完");
            message.setSuccess("false");
        } else {
            //  lists = getAllDeliverySkubarcode(delivery, mTransport.getMaterial());
            lists = getAllDeliverySkubarcode(delivery, mTransport.getItem());
            if (mTransport.getFlag() != null && mTransport.getFlag().equals("BIND")) {
                message.setMsg("此二维码已经被扫描");
                message.setSuccess("false");
                MaterialTransport mt = new MaterialTransport(mTransport.getMaterial(), mTransport.getDescription(), mTransport.getDeliveryQty(), mTransport.getSendDeliveryQty(), mTransport.getDelivery(), mTransport.getRemainingQty());
                lists.add(0, mt);

            } else {
                message.setMsg("扫描成功");
                message.setSuccess("true");
                lists.add(0, mTransport);
            }


        }
        if (lists.size() != 0 && lists != null) {
            jo.put("deliverys", lists);
        }

        jo.put("message", message);
        return jo.toString();

    }

//查询订单下面不包含此行号的所有信息
    private List<MaterialTransport> getAllDeliverySkubarcode(String delivery, String item) {
        StringBuffer sBuffer = new StringBuffer("SELECT DISTINCT tpd.material,tm.materialcode,tmp.sta,tpd.description, tp.delivery,tpd.deliveryQty,tpd.sendDeliveryQty,tpd.item FROM t_material_portdetail tmp"
                + " right JOIN t_material tm ON tmp.materialId = tm.id "
                + " right JOIN t_portdetail tpd ON tmp.transportDetailId = tpd.id "
                + " LEFT JOIN t_port tp ON tp.id = tpd.transportId WHERE tp.delivery = '" + delivery + "' ");


       /* if (!material.equals("")) {
            sBuffer.append(" and tpd.material <> '" + material + "'");
        }*/

        if (!item.equals("")) {
            sBuffer.append(" and tpd.item <> '" + item + "'");
        }


        List<MaterialTransport> query = new ArrayList<MaterialTransport>();

        try {
            query = jdbcTemplate.query(sBuffer.toString(), new RowMapper<MaterialTransport>() {

                @Override
                public MaterialTransport mapRow(ResultSet rs, int rowNum) throws SQLException {
                    // TODO Auto-generated method stub
                    String status = "已结单";
                    //根据状态判断相应的状态类型，返回前台
                    if (rs.getString("sta") != null) {
                        if (rs.getString("sta").equals("NEW") || rs.getString("sta").equals("FAIL")) {
                            status = "未结单";
                        }

                    } else {
                        status = "未扫描";
                    }
                    MaterialTransport mt = new MaterialTransport(rs.getString("material"), rs.getString("description"), String.valueOf(rs.getInt("deliveryQty")), status);
                    mt.setSendDeliveryQty(rs.getString("sendDeliveryQty"));
                    mt.setItem(rs.getString("item"));
                    return mt;
                }
            });
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
            return query;
        }
        return query;

    }


    private MaterialTransport bindDeliverAndMaterial(String delivery, String barCode) {
        MaterialTransport mTransport = null;
        //判断此delivery号是否已经结单
        boolean b1 = transportDetailService.findOrderStatusByDelivery(delivery);

        //判断此barcode是否已经被扫描
        boolean b = findBarcodeIsSend(barCode);
        //根据barcode查询物料信息
        Material material = itemBarService.findMaterialBybarCode(barCode);
        /**
         * 如果满足上述条件，true:
         *      查询此barcode最近一次被扫描的时间
         *          如果不是被此delivery号扫描，并且状态为已经结单，就判断当前扫描的时间和这个二维码最近一次的扫描时间间隔
         *          如果间隔超过2天，就可以重新扫描此二维码，
         *          如果没有超过2天，返回提示信息
         * 如果订单号已经结单:
         *      返回提示信息，已经结单
         */
        if (b && !b1) {
            Map<String, Object> map = findMaxTimeBybarcode(barCode);
            if (!map.get("delivery").toString().equals(delivery) && map.get("sta").toString().equals("SEND")) {
                Date now = new Date();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                long date1 = now.getTime();
                Date sendTime;
                Calendar c = Calendar.getInstance();

                try {
                    sendTime = sdf.parse(map.get("sendTime").toString());
                } catch (ParseException e) {
                    return null;
                }

                c.setTime(sendTime);
                c.add(Calendar.DATE, 2);
                int num = (int) ((date1 - sendTime.getTime()) / (1000 * 3600 * 24));
                if (num < 2) {
                    mTransport = new MaterialTransport();
                    mTransport.setFlag("NO");
                    mTransport.setDescription("二维码已结单，请在" + sdf.format(c.getTime()) + "之后再扫描");
                    return mTransport;
                } else {
                    //扫描之前先判断订单中的每一个物料是否已经扫完，如果全部扫完，直接返回
                    List<Transport> lists1 = findByDelivery(delivery);
                    if (lists1 != null && lists1.size() != 0) {
                        //根据订单id和物料查询明细，可能有多条，可能有1条
                        List<TransportDetail> details1 = transportDetailService.findDetailByTransportIdAndMaterialId(lists1.get(0).getId(), material.getMaterialCode());
                        if (details1 != null && details1.size() != 0) {
                            /**
                             * 循环判断所有明细是否已经扫完，如果扫完，继续下一条判断，如果没有扫完，isFull置为false，
                             * 结束循环，
                             */
                            boolean isFull = true;
                            for (TransportDetail td : details1) {
                                if (Integer.parseInt(td.getDeliveryQty()) == Integer.parseInt(td.getSendDeliveryQty())) {
                                    continue;
                                } else {
                                    isFull = false;
                                    break;
                                }
                            }

                            /**
                             * 如果isFull为true说明已经全部扫完
                             */
                            if (isFull) {
                                mTransport = new MaterialTransport();
                                mTransport.setFlag("FULL");
                                mTransport.setMaterial(material.getMaterialCode());
                                return mTransport;
                            }

                            /**
                             * 这里是为了解决一个订单下面多个相同的物料号
                             * 如果查询出来的明细有多条，说明这个订单下面有相同的物料号，循环判断这些物料是否扫完，
                             * 如果没有扫完，保存这条物料，进行下面操作，进行扫描
                             *
                             */

                            int m = 0;
                            if (details1.size() > 1) {
                                for (int j = 0; j < details1.size(); j++) {
                                    if (Integer.parseInt(details1.get(j).getDeliveryQty()) != Integer.parseInt(details1.get(j).getSendDeliveryQty())) {
                                        m = j;
                                        break;
                                    }
                                }
                            }

                            String sql1 = "insert into t_material_portdetail (id,materialId,transportDetailId,barcode,createTime,sta) values ('" + UUID.randomUUID().toString() + "','" + material.getId() + "','" + details1.get(m).getId() + "','" + barCode + "',NOW(),'NEW')";
                            if (map != null && map.size() != 0) {
                                int n = jdbcTemplate.update(sql1.toString());
                                if (n == 1) {
                                    Set<String> ids = new HashSet<String>();
                                    ids.add(details1.get(m).getId());
                                    //明细的扫描数量加1
                                    transportDetailService.saveSendDeliveryQty(ids, 1, 0);
                                    mTransport = new MaterialTransport(material.getMaterialCode(), details1.get(m).getDescription(), details1.get(m).getDeliveryQty(), details1.get(m).getSendDeliveryQty(), delivery);
                                    mTransport.setItem(details1.get(m).getItem());
                                    return mTransport;

                                }
                            }

                        }

                    }


                }
            }
        }
        if (b1) {

            mTransport = new MaterialTransport();
            mTransport.setFlag("SEND");
            return mTransport;
        }


        if (material != null) {
            if (material.getStatus() != null && !material.getStatus().equals("")) {
                List<Transport> lists = findByDelivery(delivery);
                if (lists != null && lists.size() != 0) {
                    List<TransportDetail> details = transportDetailService.findDetailByTransportIdAndMaterialId(lists.get(0).getId(), material.getMaterialCode());
                    if (details != null && details.size() != 0) {
                        /**
                         * 循环判断所有明细是否已经扫完，如果扫完，继续下一条判断，如果没有扫完，isFull置为false，
                         * 结束循环，
                         */
                        boolean isFull = true;
                        for (TransportDetail td : details) {
                            if (Integer.parseInt(td.getDeliveryQty()) == Integer.parseInt(td.getSendDeliveryQty())) {
                                continue;
                            } else {
                                isFull = false;
                                break;
                            }
                        }

                        /**
                         * 如果isFull为true说明已经全部扫完
                         */
                        if (isFull) {
                            mTransport = new MaterialTransport();
                            mTransport.setFlag("FULL");
                            mTransport.setMaterial(material.getMaterialCode());
                            return mTransport;
                        }

                        /**
                         * 当物料出现多条时，通过下面的for循环来记录第几个物料没有扫完。
                         */
                        int m = 0;
                        if (details.size() > 1) {
                            for (int j = 0; j < details.size(); j++) {
                                if (Integer.parseInt(details.get(j).getDeliveryQty()) != Integer.parseInt(details.get(j).getSendDeliveryQty())) {
                                    m = j;
                                    break;
                                }
                            }
                        }


                        StringBuffer sBuffer2 = new StringBuffer("insert into t_material_portdetail (id,materialId,transportDetailId,barcode,createTime,sta) values ('" + UUID.randomUUID().toString() + "','" + material.getId() + "','" + details.get(m).getId() + "','" + barCode + "',NOW(),'NEW')");
                        // Set<String> ids = listToSet(details);
                        Set<String> ids = new HashSet<String>();
                        ids.add(details.get(m).getId());
                        //如果此二维码没有被扫描
                        if (material.getStatus().equals("NEW")) {
                            if (!checkIsBind(material.getId(), details.get(m).getId())) {
                                //插入物料和明细的中间表，扫描一条数据
                                int i = jdbcTemplate.update(sBuffer2.toString());
                                if (i == 1) {
                                    //更新物料表中二维码的状态
                                    boolean f1 = itemBarService.updateStatusToBind(material.getMaterialCode(), barCode);
                                    if (f1) {
                                        //明细中，扫描数量加1
                                        boolean f2 = transportDetailService.saveSendDeliveryQty(ids, 1, 0);
                                        if (f2) {
                                            mTransport = new MaterialTransport(material.getMaterialCode(), details.get(m).getDescription(), details.get(m).getDeliveryQty(), details.get(m).getSendDeliveryQty(), delivery);
                                            mTransport.setItem(details.get(m).getItem());
                                        }
                                    }
                                }
                            }
                            //如果此二维码已经被扫描
                        } else if (material.getStatus().equals("BIND")) {
                            mTransport = new MaterialTransport(material.getMaterialCode(), details.get(m).getDescription(), details.get(m).getDeliveryQty(), delivery);
                            mTransport.setSendDeliveryQty(details.get(m).getSendDeliveryQty());
                            mTransport.setItem(details.get(m).getItem());
                            mTransport.setFlag("BIND");
                        }
                        //扫描的二维码与订单下面的物料不匹配
                    } else {
                        mTransport = new MaterialTransport();
                        mTransport.setFlag("BPP");         //扫描的二维码和单号的物料不对应 （不匹配）
                        return mTransport;
                    }
                }
            }

        }
        return mTransport;
    }


    private boolean findBarcodeIsSend(String barcode) {
        String sql = " select count(id) num from t_material_portdetail where barcode='" + barcode + "' and sta = 'SEND'";
        Map<String, Object> map = jdbcTemplate.queryForMap(sql);
        if (map != null) {
            if (map.get("num").toString().equals("0")) {
                return false;
            }
        }
        return true;

    }


    private Map<String, Object> findMaxTimeBybarcode(String barcode) {
        StringBuffer sb = new StringBuffer("SELECT tmp.transportDetailId,tp.delivery,tmp.sta,tmp.sendTime FROM t_material_portdetail tmp " +
                " LEFT JOIN t_portdetail tpd ON tmp.transportDetailId = tpd.id " +
                " LEFT JOIN t_port tp ON tp.id = tpd.transportId" +
                " WHERE 1=1 ");
        if (barcode != null && !barcode.equals("")) {
            sb.append(" and tmp.barcode='" + barcode + "'");
        }
        sb.append(" ORDER BY tmp.createTime DESC LIMIT 0,1");
        Map<String, Object> map = jdbcTemplate.queryForMap(sb.toString());
        return map;
    }


    private Set<String> listToSet(List<TransportDetail> lists) {
        Set<String> idSet = new HashSet<String>();
        for (int i = 0; i < lists.size(); i++) {
            idSet.add(lists.get(i).getId());
        }
        return idSet;
    }


    private boolean checkIsBind(String materialId, String transportDetailId) {
        String sql = "select count(materialId) from t_material_portdetail where materialId = ? and transportDetailId = ?";
        int i = (int) jdbcTemplate.queryForObject(sql, new Object[]{materialId, transportDetailId}, Integer.class);
        if (i != 0) {
            return true;
        }
        return false;

    }


    @Override
    public String deleteDeliverySkuBarcode(String delivery, String material, String barcodes) {
        // TODO Auto-generated method stub
        //  String message = "{\"msg\": \"删除失败\",\"success\": false}";

        Message message = new Message();
        message.setMsg("删除失败");
        message.setSuccess("false");
        JSONObject jo = new JSONObject();
        List<Map<String, Object>> objs = findByDeliveryAndMaterial(delivery, material, barcodes);

        if (objs != null && objs.size() != 0) {
            if (objs.get(0).get("sta").equals("SEND")) {
                message.setMsg("已结单，不能删除");
                message.setSuccess("false");

            } else {

                List<String> ids = new ArrayList<String>();   //存放要删除的主键id
                List<String> materialIds = new ArrayList<String>();   //物料表中的id
                Set<String> transportDetailIds = new HashSet<String>();   //明细表中的id
                Map<String, String> sendNum = new HashMap<String, String>();      //前台不传入barcoe时，明细id，以及其所对应的要修改的扫描数量
                Map<String, String> delBarcodeNum = new HashMap<String, String>();   //前台传入多个barcode时，用来存放明细id和要删除的数量
                for (Map<String, Object> map : objs) {
                    if (!map.isEmpty()) {
                        int i = 0;
                        /**
                         * 判断明细id是否存在于集合中，如果存在就把值加一，这样就可以根据前台传入的多个barcode按照明细进行分类，删除对应的数量
                         * 这一步是因为一个订单下面有多个相同的物料所操作的，如果前台传入多个二维码，并且这些二维码是属于相同物料，需要处理
                         * 因为如果不处理的话，无法保证这些二维码分属于哪些物料。
                         */
                        if (delBarcodeNum.containsKey(map.get("transportDetailId").toString())) {
                            int num = Integer.parseInt(delBarcodeNum.get(map.get("transportDetailId").toString()));
                            delBarcodeNum.put(map.get("transportDetailId").toString(),
                                    String.valueOf(num + 1));
                        } else {
                            delBarcodeNum.put(map.get("transportDetailId").toString(), String.valueOf(++i));
                        }

                        //从查询的结果中分别得到要修改的主键id，进行批量处理
                        String id = map.get("id").toString();
                        String materialId = map.get("materialId").toString();
                        String transportDetailId = map.get("transportDetailId").toString();
                        if (transportDetailId != null && !transportDetailId.equals("")) {
                            transportDetailIds.add(transportDetailId);
                        }

                        if (id != null && !id.equals("")) {
                            ids.add(id);
                        }
                        if (materialId != null && !materialId.equals("")) {
                            materialIds.add(materialId);
                        }

                        /**
                         * 当前台不传入barcode时，删除这个物料下面的所有二维码，保存每一个明细对应的发送数量进行删除
                         */
                        sendNum.put(map.get("transportDetailId").toString(), map.get("sendDeliveryQty").toString());

                    }


                }
                if (ids != null && ids.size() != 0) {
                    String sqlDel = "delete from t_material_portdetail where id = ?";
                    try {

                        int[] batchUpdate = jdbcTemplate.batchUpdate(sqlDel, new BatchPreparedStatementSetter() {

                            @Override
                            public void setValues(PreparedStatement ps, int i) throws SQLException {
                                // TODO Auto-generated method stub
                                ps.setString(1, ids.get(i));
                            }

                            @Override
                            public int getBatchSize() {
                                // TODO Auto-generated method stub
                                return ids.size();
                            }
                        });
                        if (batchUpdate != null && batchUpdate.length != 0) {
                            boolean f1 = itemBarService.updateStatusToNew(materialIds);
                            if (f1) {
                                boolean f2 = false;
                                //如果前台只传入delivery，删除重扫其下面的所有已经扫描的二维码
                                if (material.equals("") && barcodes.equals("")) {
                                    f2 = transportDetailService.saveSendDeliveryQty(transportDetailIds);
                                //参数都不为空时，根据明细id，以及要修改的扫描数量，分别进行操作
                                } else if (!material.equals("") && !barcodes.equals("")) {
                                    f2 = transportDetailService.saveSendDeliveryQty(transportDetailIds, delBarcodeNum);
                               //物料不为空时，说明要把扫描数量置为0，这里同样要保存其对应的以扫数量，都是为了防止订单下面有相同的物料号
                                } else if (!material.equals("") && barcodes.equals("")) {
                                    f2 = transportDetailService.saveSendDeliveryQty(transportDetailIds, sendNum);
                                }

                                if (f2) {
                                    message.setMsg("删除成功");
                                    message.setSuccess("true");
                                }
                            }
                        }
                    } catch (Exception e) {
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return jo.put("message", message).toString();
                    }
                }
            }

        } else {
            message.setMsg("没有扫描不能删除");
            message.setSuccess("false");
        }
        //删除重扫完，需要返回改订单下面的所有物料信息，处理的物料放到第一位，并且要把当前下面是处理流程
        List<MaterialTransport> list = getAllDeliverySkubarcode(delivery, "");
        int i = 0;
        /**
         * 遍历集合，从集合中找到当前正在操作的物料，放到集合的第一位，然后把那个位置上的移除。
         */

        if (list != null && list.size() != 0) {
            if(material != null && !"".equals(material)){
                for (MaterialTransport m : list) {
                    i++;
                    if (m.getMaterial().equals(material)) {
                        list.add(0, m);
                        list.remove(i);
                        break;
                    }
                }
            }
            jo.put("deliverys", list);
        }
        jo.put("message", message);
        return jo.toString();
    }


    @Override
    public List<Map<String, Object>> findByDeliveryAndMaterial(String delivery, String material, String barcodes) {
        // TODO Auto-generated method stub
        Object[] objects = null;

        StringBuffer sBuffer = new StringBuffer("SELECT tmp.*, tpd.sendDeliveryQty FROM t_material_portdetail as tmp " +
                "LEFT JOIN t_material as tm ON tmp.materialId = tm.id " +
                "LEFT JOIN t_portdetail as tpd ON tmp.transportDetailId = tpd.id " +
                "LEFT JOIN t_port as tp ON tp.id = tpd.transportId WHERE tp.delivery = ?");

        if (material != null && !material.equals("")) {
            sBuffer.append(" AND tpd.material = ?");
            objects = new Object[]{delivery, material};
        } else {
            objects = new Object[]{delivery};
        }

        if (barcodes != null && !barcodes.equals("")) {
            String[] str = barcodes.split(",");
            if (str.length != 0) {
                String bc = "";
                for (int i = 0; i < str.length; i++) {
                    bc = bc + "'" + str[i] + "',";
                }

                sBuffer.append(" and tmp.barcode in (" + bc.substring(0, bc.length() - 1) + ")");
            }
        }


        List<Map<String, Object>> objs = null;

        try {
            objs = jdbcTemplate.queryForList(sBuffer.toString(), objects);
            return objs;
        } catch (Exception e) {
            // TODO: handle exception
            return null;

        }

    }


    @Override
    public String findPrintSkuLabelInfo(String deliveryStart, String deliveryEnd, String barcode, String materials, String user) {
        // TODO Auto-generated method stub
        Message message = new Message();
        JSONObject jo = new JSONObject();

        StringBuffer sb = new StringBuffer("SELECT DISTINCT tp.delivery,tp.poNum,tp.shipToName,tp.delAddress,tpd.sendDeliveryQty,tpd.deliveryQty,tpd.material from t_portdetail tpd " +
                " LEFT JOIN t_port tp on tp.id = tpd.transportId" +
                " LEFT JOIN t_material tm on tm.materialcode = tpd.material ");

        if (deliveryEnd == null || deliveryEnd.equals("")) {
            sb.append(" where tp.delivery = '" + deliveryStart + "'");
        } else {
            sb.append(" WHERE tp.delivery BETWEEN '" + deliveryStart + "' AND '" + deliveryEnd + "'");
        }

        if (materials != null && !materials.equals("")) {
            String[] materialStr = materials.split(",");
            if (materialStr.length != 0) {
                String bc = "";
                for (int i = 0; i < materialStr.length; i++) {
                    bc = bc + "'" + materialStr[i] + "',";
                }
                sb.append(" and tpd.material in (" + bc.substring(0, bc.length() - 1) + ")");
            }
        }

        if (barcode != null && !barcode.equals("")) {
            sb.append(" and tm.barcode ='" + barcode + "'");
        }

        if (user != null && !user.equals("")) {
            sb.append(" and tp.plantCode='" + user + "'");
        }

        sb.append(" ORDER BY tp.delivery,tpd.material");

        List<MaterialTransport> objs = null;
        objs = jdbcTemplate.query(sb.toString(), new RowMapper<MaterialTransport>() {

            @Override
            public MaterialTransport mapRow(ResultSet rs, int rowNum) throws SQLException {
                // TODO Auto-generated method stub
                MaterialTransport mt = new MaterialTransport(rs.getString("material"),
                        rs.getInt("deliveryQty"),
                        // rs.getInt("sendDeliveryQty"),
                        rs.getString("delivery"),
                        rs.getString("shipToName"), rs.getString("delAddress"),
                        rs.getString("poNum"));
                return mt;
            }
        });

        if (objs != null && objs.size() != 0) {
            jo.put("datas", objs);
            message.setMsg("打印成功");
            message.setSuccess("true");
        } else {
            message.setMsg("没有数据");
            message.setSuccess("false");
        }

        jo.put("message1", message);
        return jo.toString();
    }


    private String getWarehouseInvoice(String billDate, String bilCode, String orderCode, String submitTime,
                                       String refCertificate, String destName, String srcName, String srcCode, String destCode,
                                       String boxCodes, String soldTo) {
        OkHttpClient client = new OkHttpClient();
        FormBody formBody = new FormBody.Builder()
                .add("refCertificate", refCertificate)
                .add("billDate", billDate)
                .add("billCode", bilCode)
                .add("orderCode", orderCode)
                .add("submitTime", submitTime)
                .add("destName", destName)
                .add("srcName", srcName)
                .add("srcCode", srcCode)
                .add("destCode", destCode)
                .add("boxCodes", boxCodes)
                .add("soldTo", soldTo)
                .build();


        String credential = Credentials.basic("ehsure@2017", "8BiUk$.)tpJ8wt$Cs[p0Sjv+[*iF^p");
        Request request = new Request.Builder()
                .header("Authorization", credential)
                .url("https://qr.huggies.com.cn:8099/api/proj/openapi/rdcoutbill")
                .post(formBody)
                .build();

        try {
            Response response = client.newCall(request).execute();
            return response.body().string();
        } catch (IOException e1) {
            e1.printStackTrace();
            // TODO Auto-generated catch block
            return null;
        }
    }


    @Override
    public String getPrintOrder(String delivery,boolean f) {
        // TODO Auto-generated method stub
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = sdf.format(new Date());
        List<Transport> transports = findByDelivery(delivery);
        String message = "{\"msg\": \"结单失败\",\"success\": false}";
        String returnStr = null;
        if (transports != null && transports.size() != 0) {
            //根据订单号，得到要结单的物料明细
            List<TransportDetail> details = transportDetailService.findDetailByTransportIdAndMaterialId(transports.get(0).getId(), "");
            /**
             * f == true，正常结单：物料必须扫完
             * f== false,非正常结单：物料没有扫完，也可以结单
             */

            if(f){
                for (TransportDetail td :
                        details) {
                    if (!td.getDeliveryQty().equals(td.getSendDeliveryQty())) {
                        message = "{\"msg\": \"物料没有扫完，不能结单\",\"success\": false}";
                        return message;
                    }
                }
            }
            Iterator<String> iterator = listToSet(details).iterator();
            String idStr = "";
            while (iterator.hasNext()) {
                idStr = idStr + "'" + iterator.next() + "',";

            }

            if (details != null && details.size() != 0) {
                String sql = "select id,transportDetailId,barcode from t_material_portdetail where transportDetailId in (" + idStr.substring(0, idStr.length() - 1) + ")";
                List<Map<String, Object>> listMaps = jdbcTemplate.queryForList(sql);
                if (listMaps != null && listMaps.size() != 0) {
                    List<String> tmpIds = new ArrayList<String>();
                    List<String> barcodes = new ArrayList<String>();
                    for (Map<String, Object> map : listMaps) {
                        barcodes.add((String) map.get("barcode"));
                        tmpIds.add((String) map.get("id"));
                    }
                    if (barcodes.size() != 0 && tmpIds.size() != 0) {
                        //用来接收第三方接口返回的code码
                        int code = 123;
                        JSONObject jo = null;
                        returnStr = getWarehouseInvoice(transports.get(0).getSendDate(), transports.get(0).getDelivery(), details.get(0).getOrderNo()
                                , date, transports.get(0).getPoNum(), transports.get(0).getShipToName(), transports.get(0).getPlantName()
                                , transports.get(0).getPlantCode(), transports.get(0).getShipTo()
                                , Joiner.on(",").join(barcodes), transports.get(0).getSoldTo());
                        jo = new JSONObject().parseObject(returnStr);
                        //得到返回码
                        code = (int) jo.get("code");
                        //得到返回的错误信息
                        String errMsg = (String) jo.get("errMsg");
                        //根据返回的code值，更新表中的状态
                        boolean flag = transportDetailService.updateMaterialAndTransportDetailStatusById(tmpIds, code);

                        if (flag) {
                            message = "{\"msg\": \"结单成功\",\"success\": true}";
                        } else {
                            message = "{\"msg\": \"" + errMsg + "\",\"success\": false}";
                        }
                    }
                }else{
                    message = "{\"msg\": \"请先扫描\",\"success\": false}";
                }
            }
        }

        return message;
    }

    @Override
    public String find(String createDateStart, String createDateEnd, String deliveryStart, String deliveryEnd, String plantCode, String scanDateStart, String scanDateEnd) {

        Message message = new Message();
        JSONObject jo = new JSONObject();
        message.setSuccess("false");
        message.setMsg("查询失败");

        StringBuffer sb = new StringBuffer("SELECT tp.createTime as createDate, tp.plantCode,tp.plantName,tp.delivery,tmp.createTime,tpd.material,tmp.barcode, " +
                " tpd.description,tpd.deliveryQty,tpd.sendDeliveryQty,tp.poNum,tp.shipTo,tp.shipToName,tp.delAddress,tp.soldTo,tpd.productCode,tmp.sta " +
                " from t_material_portdetail tmp" +
                " RIGHT JOIN t_portdetail tpd on tmp.transportDetailId = tpd.id" +
                " LEFT JOIN t_port tp on tpd.transportId = tp.id where 1=1 ");


        if (deliveryEnd.equals("") && !deliveryStart.equals("")) {
            sb.append(" and tp.delivery = '" + deliveryStart + "'");

        } else if (!deliveryStart.equals("") && !deliveryEnd.equals("")) {
            sb.append("and tp.delivery BETWEEN cast('" + deliveryStart + "' as SIGNED INTEGER) and cast('" + deliveryEnd + "' as SIGNED INTEGER)");
        }


        if (createDateStart != null && !"".equals(createDateStart)&& !"".equals(createDateEnd) && createDateEnd != null) {
            createDateStart = createDateStart + " 00:00:00";
            createDateEnd = createDateEnd + " 23:59:59";
            sb.append(" AND tp.createTime BETWEEN '" + createDateStart + "' AND '" + createDateEnd + "'");
        }

        if (plantCode != null && !plantCode.equals("")) {
            sb.append(" AND tp.plantCode = '" + plantCode + "'");
        }

        if(scanDateStart != null && !"".equals(scanDateStart) && !"".equals(scanDateEnd) && scanDateEnd != null){
            scanDateStart = scanDateStart + ":00";
            scanDateEnd = scanDateEnd + ":59";
            sb.append(" AND tmp.createTime BETWEEN '" + scanDateStart + "' AND '" + scanDateEnd + "'");
        }

        List<MaterialTransport> materialTransports = null;
        try {

            materialTransports = jdbcTemplate.query(sb.toString(), new RowMapper<MaterialTransport>() {


                @Override
                public MaterialTransport mapRow(ResultSet rs, int rowNum) throws SQLException {
                    MaterialTransport mt = new MaterialTransport();
                    //   mt.setPortId(rs.getString("id"));
                    mt.setPlantCode(rs.getString("plantCode"));
                    mt.setPlantName(rs.getString("plantName"));
                    mt.setDelivery(rs.getString("delivery"));
                    if (rs.getString("createTime") != null) {
                        mt.setCreateTime(rs.getString("createTime").substring(0, rs.getString("createTime").length() - 2));
                    } else {
                        mt.setCreateTime("");
                    }
                    mt.setMaterial(rs.getString("material"));
                    mt.setBarCode(rs.getString("barcode"));
                    mt.setDescription(rs.getString("description"));
                    mt.setDeliveryQty(String.valueOf(rs.getInt("deliveryQty")));
                    mt.setSendDeliveryQty(rs.getString("sendDeliveryQty"));
                    mt.setPoNum(rs.getString("poNum"));
                    mt.setShipToName(rs.getString("shipToName"));
                    mt.setShipTo(rs.getString("shipTo"));
                    mt.setDelAddress(rs.getString("delAddress"));
                    mt.setSoldTo(rs.getString("soldTo"));
                    mt.setProductCode(rs.getString("productCode"));
                    mt.setCreateDate(rs.getString("createDate").substring(0, rs.getString("createDate").length() - 2));
                    if (rs.getString("sta") != null) {
                        if (rs.getString("sta").toString().equals("NEW")) {
                            mt.setFlag("已扫描");
                        }
                        if (rs.getString("sta").toString().equals("SEND")) {
                            mt.setFlag("已结单");
                        }
                        if (rs.getString("sta").toString().equals("FAIL")) {
                            mt.setFlag("结单失败");
                        }
                    } else {
                        mt.setFlag("未扫描");
                    }

                    return mt;
                }
            });

        } catch (Exception e) {
            e.printStackTrace();
            jo.put("message1", message);
            return jo.toString();
        }


        if (materialTransports == null || materialTransports.size() == 0) {
            message.setSuccess("false");
            message.setMsg("没有数据");
        } else {
            jo.put("datas", materialTransports);
            message.setSuccess("true");
            message.setMsg("查询成功");
        }
        jo.put("message1", message);

        return jo.toString();
    }

    @Override
    public String printLabels(String substring, String barcode, String materials, String user) {
        Message message = new Message();
        JSONObject jo = new JSONObject();

        StringBuffer sb = new StringBuffer("SELECT DISTINCT tp.delivery,tp.poNum,tp.shipToName,tp.delAddress,tpd.sendDeliveryQty,tpd.deliveryQty,tpd.material from t_portdetail tpd " +
                " LEFT JOIN t_port tp on tp.id = tpd.transportId" +
                " LEFT JOIN t_material tm on tm.materialcode = tpd.material ");

        if (substring != null && !substring.equals("")) {
            sb.append(" where tp.delivery in (" + substring + ")");
        }

        if (materials != null && !materials.equals("")) {
            String[] materialStr = materials.split(",");
            if (materialStr.length != 0) {
                String bc = "";
                for (int i = 0; i < materialStr.length; i++) {
                    bc = bc + "'" + materialStr[i] + "',";
                }
                sb.append(" and tpd.material in (" + bc.substring(0, bc.length() - 1) + ")");
            }
        }

        if (barcode != null && !barcode.equals("")) {
            sb.append(" and tm.barcode ='" + barcode + "'");
        }

        if (user != null && !user.equals("")) {
            sb.append(" and tp.plantCode='" + user + "'");
        }

        sb.append(" ORDER BY tp.delivery,tpd.material");

        List<MaterialTransport> objs = null;
        objs = jdbcTemplate.query(sb.toString(), new RowMapper<MaterialTransport>() {

            @Override
            public MaterialTransport mapRow(ResultSet rs, int rowNum) throws SQLException {
                // TODO Auto-generated method stub
                MaterialTransport mt = new MaterialTransport(rs.getString("material"),
                        rs.getInt("deliveryQty"),
                        // rs.getInt("sendDeliveryQty"),
                        rs.getString("delivery"),
                        rs.getString("shipToName"), rs.getString("delAddress"),
                        rs.getString("poNum"));
                return mt;
            }
        });

        if (objs != null && objs.size() != 0) {
            jo.put("datas", objs);
            message.setMsg("打印成功");
            message.setSuccess("true");
        } else {
            message.setMsg("没有数据");
            message.setSuccess("false");
        }

        jo.put("message1", message);
        return jo.toString();

    }




    @Override
    public String findDateInfoByDelivery(String delivery) {
        // TODO Auto-generated method stub
        List<MaterialTransport> lists = getAllDeliverySkubarcode(delivery, "");
        Message message = new Message();
        message.setMsg("没有数据");
        message.setSuccess("false");
        JSONObject jo = new JSONObject();
        if (lists != null && lists.size() != 0) {
            jo.put("deliverys", lists);
            message.setMsg("查询成功");
            message.setSuccess("true");
        }
        jo.put("message", message);

        return jo.toString();
    }

    @Override
    public boolean deleteTransportByid(String id) {
        String sql = "delete from t_port where id = '" + id + "'";
        int i = jdbcTemplate.update(sql);
        if (i != 0) {
            return true;
        }
        return false;
    }


}
